package vboot.core.module.sys.api.main;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vboot.core.common.dao.JdbcDao;
import vboot.core.common.dao.Sqler;

import java.util.ArrayList;
import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
public class SysApiMainService {


    public List<SysApiMain> findTree(Sqler sqler) {
        List<SysApiMain> list = jdbcDao.getTp().query(sqler.getSql(), sqler.getParams(), new BeanPropertyRowMapper<>(SysApiMain.class));
        return buildByRecursive(list);
    }

    //使用递归方法建树
    private List<SysApiMain> buildByRecursive(List<SysApiMain> nodes) {
        List<SysApiMain> list = new ArrayList<>();
        for (SysApiMain node : nodes) {
            if (node.getPid() == null) {
                list.add(findChildrenByTier(node, nodes));
            } else {
                boolean flag = false;
                for (SysApiMain node2 : nodes) {
                    if (node.getPid().equals(node2.getId())) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    list.add(findChildrenByTier(node, nodes));
                }
            }
        }
        return list;
    }

    //递归查找子节点
    private SysApiMain findChildrenByTier(SysApiMain node, List<SysApiMain> nodes) {
        for (SysApiMain item : nodes) {
            if (node.getId().equals(item.getPid())) {
                if (node.getChildren() == null) {
                    node.setChildren(new ArrayList<>());
                }
                node.getChildren().add(findChildrenByTier(item, nodes));
            }
        }
        return node;
    }


    @Autowired
    private JdbcDao jdbcDao;
}
